package com.github.skystardust.lotteryex.lottery.bundle;

import com.github.skystardust.lotteryex.lottery.item.RequireItem;
import com.github.skystardust.lotteryex.lottery.item.api.Require;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.bukkit.entity.Player;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

@EqualsAndHashCode(of = "uuid")
@ToString
public class RequireBundle implements Require<RequireBundle> {
    private UUID uuid;
    private List<RequireItem> requireItemList;

    public RequireBundle(UUID uuid, List<RequireItem> requireItemList) {
        this.uuid = uuid;
        this.requireItemList = requireItemList;
    }

    public RequireBundle(List<RequireItem> requireItemList) {
        this(UUID.randomUUID(), requireItemList);
    }

    public RequireBundle(Map<String, Object> stringObjectMap) {
        this.uuid = UUID.fromString(((String) stringObjectMap.get("uuid")));
        this.requireItemList = ((List<RequireItem>) stringObjectMap.get("requireItemList"));
    }

    private RequireBundle(Builder builder) {
        setUuid(builder.uuid);
        setRequireItemList(builder.requireItemList);
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public boolean hasRequireObject(Player player) {
        return requireItemList.stream()
                .allMatch(requireItem -> requireItem.hasRequireObject(player));
    }

    public void takeItem(Player player) {
        if (!hasRequireObject(player)) {
            return;
        }
        requireItemList.forEach(requireItem -> requireItem.takeItem(player));
    }

    public UUID getUuid() {
        return uuid;
    }

    public void setUuid(UUID uuid) {
        this.uuid = uuid;
    }

    public List<RequireItem> getRequireItemList() {
        return requireItemList;
    }

    public void setRequireItemList(List<RequireItem> requireItemList) {
        this.requireItemList = requireItemList;
    }

    @Override
    public Map<String, Object> serialize() {
        TreeMap<String, Object> stringObjectTreeMap = new TreeMap<>();
        stringObjectTreeMap.put("uuid", uuid.toString());
        stringObjectTreeMap.put("requireItemList", requireItemList);
        return stringObjectTreeMap;
    }

    public static final class Builder {
        private UUID uuid;
        private List<RequireItem> requireItemList;

        private Builder() {
        }

        @Nonnull
        public Builder withUuid(@Nonnull UUID val) {
            uuid = val;
            return this;
        }

        @Nonnull
        public Builder withRequireItemList(@Nonnull List<RequireItem> val) {
            requireItemList = val;
            return this;
        }

        @Nonnull
        public RequireBundle build() {
            return new RequireBundle(this);
        }
    }
}
